package ru.paswd.marketprice.ui.adapter

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_product.view.*
import ru.paswd.marketprice.R
import ru.paswd.marketprice.data.models.Product
import ru.paswd.marketprice.ui.activity.PriceMapActivity
import ru.paswd.marketprice.utils.NumericUtils
import ru.paswd.marketprice.utils.convertDpToPixel

class ProductAdapter(private val context: Context, products: List<Product>)
    : RecyclerView.Adapter<ProductAdapter.ViewHolder>() {

    var products: List<Product> = listOf()
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    init {
        this.products = products
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        ViewHolder(LayoutInflater.from(parent.context)
            .inflate(R.layout.item_product, parent, false))

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val product = products[position]

        holder.title.text = product.name
        val priceMin = "▼ " + NumericUtils.createDisplayablePrice(product.priceMin)
        val priceMax = "▲ " + NumericUtils.createDisplayablePrice(product.priceMax)
        holder.priceMin.text = priceMin
        holder.priceMax.text = priceMax

        holder.layout.setOnClickListener { onClick(position) }

        setMargins(holder.layout, position)
    }

    override fun getItemCount() = products.size

    private fun onClick(position: Int) {
        val intent = Intent(context, PriceMapActivity::class.java)
        intent.putExtra(PriceMapActivity.PRODUCT_EXTRA, products[position])
        context.startActivity(intent)
    }

    private fun setMargins(v: ViewGroup, position: Int) {
        val layoutParams = v.layoutParams as ViewGroup.MarginLayoutParams

        val margin = convertDpToPixel(
                context.resources.getDimension(R.dimen.productListSide), context).toInt()

        if (position == 0) {
            layoutParams.marginStart = margin
        }

        if (position == products.size - 1) {
            layoutParams.marginEnd = margin
        }
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val layout = view.productLayout!!
        val image = view.productImage!!
        val title = view.productTitle!!
        val priceMin = view.productPriceMin!!
        val priceMax = view.productPriceMax!!
    }
}